package com.thread.exe;

import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

public class LinkedQueue<E> {
	private static class Node<E> {
		final E item;
		final AtomicReference<Node<E>> next;
		public Node(E item, AtomicReference<Node<E>> next) {
			super();
			this.item = item;
			this.next = next;
		}
	}
	
	private final Node<E> dummy = new Node<E>(null, null);
	private final AtomicReference<Node<E>> tail = new AtomicReference<>(dummy);
	
	public boolean put(E item) {
		Node<E> newNode = new Node<E>(item, null);
		while(true) {
			Node<E> tailNode = tail.get();

			Node<E> tailNext = tailNode.next.get();
			if(tailNext != null) {
				tail.compareAndSet(tailNode, tailNext);
			}else {
				if(tailNode.next.compareAndSet(null, newNode)) { //这里不报空指针是因为Node在初始化的时候next指向的是一个装有null元素的原子变量。
					tail.compareAndSet(tailNode, newNode);
					return true;
				}
			}
		}
	}
	
	private static class NodeUpdater<E>{
		private final E item;
		private volatile Node<E> next;
		public NodeUpdater(E item, Node<E> next) {
			super();
			this.item = item;
			this.next = next;
		}
	}
	
	private static AtomicReferenceFieldUpdater<NodeUpdater, NodeUpdater> nextUpdater = 
			AtomicReferenceFieldUpdater.newUpdater(NodeUpdater.class, NodeUpdater.class, "next");
}
